package org.jason.interaction.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import org.elasticsearch.index.query.QueryBuilders;
import org.jason.common.constants.ArticleInteractionConstants;
import org.jason.common.redis.RedisCache;
import org.jason.interaction.mq.producer.ArticleProducer;
import org.jason.interaction.repository.ArticleCollectionRepository;
import org.jason.interaction.service.InteractionService;
import org.jason.model.common.dtos.ResponseResult;
import org.jason.model.common.enums.HttpCodeEnum;
import org.jason.model.interaction.dtos.ArticleInteractionDto;
import org.jason.model.interaction.es.ArticleCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

@Service
@Transactional
public class InteractionServiceImpl implements InteractionService {

    @Autowired
    private ArticleProducer articleProducer;

    @Autowired
    private ArticleCollectionRepository articleCollectionRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticTemplate;

    @Autowired
    private RedisCache redisCache;

    /**
     * 文章互动
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult articleInteraction(ArticleInteractionDto dto) {
        //添加到文章互动队列
        articleProducer.ArticleInteraction(dto);
        int userId = StpUtil.getLoginIdAsInt();
        //如果当前操作是收藏
        if (dto.getType() == ArticleInteractionConstants.COLLECTION) {
            //查询文章是否已收藏
            NativeSearchQuery query = new NativeSearchQueryBuilder()
                    .withQuery(QueryBuilders.termQuery("userId", dto.getArticleId()))
                    .withQuery(QueryBuilders.termQuery("articleId", dto.getArticleId()))
                    .build();
            SearchHits<ArticleCollection> hits = elasticTemplate.search(query, ArticleCollection.class);
            boolean empty = hits.isEmpty();
            if (empty) {
                //添加到收藏索引
                ArticleCollection articleCollection = new ArticleCollection()
                        .setArticleId(dto.getArticleId())
                        .setUserId(userId);
                articleCollectionRepository.save(articleCollection);
                return ResponseResult.get(HttpCodeEnum.SUCCESS, "收藏成功！");
            } else {
                String id = hits.getSearchHit(0).getId();
                assert id != null;
                elasticTemplate.delete(id, ArticleCollection.class);
                //添加到取消收藏队列
                articleProducer.cancelArticleInteraction(dto);
                return ResponseResult.get(HttpCodeEnum.CANCEL, "取消收藏");
            }
        } else if (dto.getType() == ArticleInteractionConstants.LIKES) {
            //如果当前操作是点赞
            Set<Integer> articleLikeSet = redisCache.getCacheSet("article_likes_" + userId);
            boolean exist = articleLikeSet.contains(dto.getArticleId());
            if (exist) {
                redisCache.delCacheSetValue("article_likes_" + userId, dto.getArticleId());
                //添加到取消点赞队列
                articleProducer.cancelArticleInteraction(dto);
                return ResponseResult.get(HttpCodeEnum.CANCEL, "取消点赞");
            }
            redisCache.addCacheSetValue("article_likes_" + userId, dto.getArticleId());
            return ResponseResult.get(HttpCodeEnum.SUCCESS, "点赞成功！");
        }
        return ResponseResult.get(HttpCodeEnum.SUCCESS);
    }
}
